package com.binance.mbxgateway.web;

import java.io.IOException;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.method.HandlerMethod;

import com.binance.master.error.GeneralCode;
import com.binance.master.models.APIResponse;

import lombok.extern.slf4j.Slf4j;

@RestControllerAdvice
@Slf4j
public class MbxHandlerAdvice {

    /**
     * 对于业务代码没有捕获的HttpStatusCodeException，这里进行统一处理
     * 
     * @param exception
     * @param handler
     * @return
     * @throws IOException
     */
    @ExceptionHandler(value = HttpStatusCodeException.class)
    public APIResponse<?> exception(HttpStatusCodeException exception, HandlerMethod handler) throws IOException {
        String errJson = exception.getResponseBodyAsString();
        log.error("The HttpStatusCodeException response body is {}，the exception is {}:", errJson,
                this.parseExceptionAsString(exception));
        return APIResponse.getErrorJsonResult(APIResponse.Type.GENERAL, GeneralCode.SYS_ERROR.getCode(), errJson);
    }

    private String parseExceptionAsString(Exception e) {
        StringBuilder sb = new StringBuilder();
        sb.append(e.getClass().getName());
        sb.append(":");
        sb.append(e.toString());
        sb.append("\n");
        StackTraceElement[] stes = e.getStackTrace();
        if (stes != null) {
            for (StackTraceElement ste : stes) {
                sb.append("\tat ");
                sb.append(ste.toString());
                sb.append("\n");
            }
        }
        return sb.toString();
    }
}
